<template>
  <div class="profile-container">
    <div class="profile-header">
      <h1 class="page-title">个人信息</h1>
    </div>

    <el-card class="profile-card">
      <div class="profile-content">
        <div class="avatar-section">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="userForm.avatarUrl" :src="getImageUrl(userForm.avatarUrl)" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="avatar-text">点击更换头像</div>
        </div>

        <el-form 
          :model="userForm" 
          :rules="rules"
          ref="userFormRef"
          label-width="100px"
          class="profile-form"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" disabled></el-input>
          </el-form-item>

          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="userForm.nickname" placeholder="请输入昵称"></el-input>
          </el-form-item>

          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="userForm.phone" placeholder="请输入手机号码"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>

          <el-form-item label="收货地址" prop="address">
            <el-input 
              v-model="userForm.address" 
              type="textarea" 
              :rows="2"
              placeholder="请输入收货地址"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="saveProfile" :loading="saving">保存修改</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>
      
      <el-form 
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="passwordForm.oldPassword" 
            type="password"
            placeholder="请输入原密码"
            show-password
          ></el-input>
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password"
            placeholder="请输入新密码"
            show-password
          ></el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password"
            placeholder="请再次输入新密码"
            show-password
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="changePassword" :loading="changingPassword">
            修改密码
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'UserWebProfile'
}
</script>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
import md5 from 'js-md5';

const router = useRouter()
const baseUrl = 'http://localhost:9191'
const uploadUrl = `${baseUrl}/file/upload` // 文件上传地址

// 用户表单
const userFormRef = ref(null)
const userForm = reactive({
  id: '',
  username: '',
  nickname: '',
  phone: '',
  email: '',
  address: '',
  avatarUrl: ''
})

// 密码表单
const passwordFormRef = ref(null)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入收货地址', trigger: 'blur' }
  ]
}

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const saving = ref(false)
const changingPassword = ref(false)

// 处理图片URL
const getImageUrl = (imgPath) => {
  if (!imgPath) return '';
  
  if (imgPath.startsWith('http://') || imgPath.startsWith('https://')) {
    return imgPath;
  }
  
  if (imgPath.startsWith('/file/')) {
    return `${baseUrl}${imgPath}`;
  }
  
  return `${baseUrl}/file/${imgPath}`;
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const userStr = sessionStorage.getItem('user')
    if (!userStr) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }
    const user = JSON.parse(userStr)
    
    const response = await request.get(`/userinfo/${user.username}`)
    if (response && response.code === '200') {
      const userData = response.data
      Object.assign(userForm, userData)
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 保存个人信息
const saveProfile = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    
    saving.value = true
    const response = await request.post('/user', userForm)
    
    if (response && response.code === '200') {
      ElMessage.success('保存成功')
      // 更新sessionStorage中的用户信息
      const userStr = sessionStorage.getItem('user')
      if (userStr) {
        const user = JSON.parse(userStr)
        user.nickname = userForm.nickname
        user.avatarUrl = userForm.avatarUrl
        sessionStorage.setItem('user', JSON.stringify(user))
      }
    } else {
      ElMessage.error(response?.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存个人信息失败:', error)
    ElMessage.error('保存失败，请检查表单内容')
  } finally {
    saving.value = false
  }
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    
    changingPassword.value = true
    const response = await request.get('/user/resetPassword', {
      params: {
        id: userForm.id,
        newPassword: md5(passwordForm.newPassword)
      }
    })
    if (response && response.code === '200') {
      ElMessage.success('密码修改成功，请重新登录')
      // 清除登录信息
      sessionStorage.removeItem('user')
      // 跳转到登录页
      router.push('/login')
    } else {
      ElMessage.error(response?.msg || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改失败，请检查输入')
  } finally {
    changingPassword.value = false
  }
}

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJpgOrPng) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isJpgOrPng && isLt2M
}

// 头像上传成功的回调
const handleAvatarSuccess = (response) => {
  if (response && response.code === '200') {
    userForm.avatarUrl = response.data
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response?.msg || '头像上传失败')
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.profile-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.profile-card {
  margin-bottom: 20px;
}

.profile-content {
  display: flex;
  gap: 40px;
}

.avatar-section {
  text-align: center;
}

.avatar-uploader {
  width: 150px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-text {
  margin-top: 10px;
  color: #666;
  font-size: 14px;
}

.profile-form {
  flex: 1;
}

.password-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .profile-content {
    flex-direction: column;
    align-items: center;
  }
  
  .profile-form {
    width: 100%;
  }
}
</style> 